package ctrconfig

import (
	"github.com/astaxie/beego/logs"
	"cloud_worm/util/uhttp"
	"cloud_worm/util/uweb/upage"
	"fmt"
	"cloud_worm/util/umodels/mysqldb/dbmanager"
	"encoding/json"
	"io/ioutil"
)

func (l *LoginCtr) isAdmin() bool {
	if l.UserInfo.Role == dbmanager.RoleAdmin {
		return true
	}
	return false
}

func (l *LoginCtr) isGuest() bool {
	if l.UserInfo.Role == dbmanager.RoleGuest {
		return true
	}
	return false
}

func (l *LoginCtr) isManager() bool {
	if l.UserInfo.Role == dbmanager.RoleManager {
		return true
	}
	return false
}

func (l *LoginCtr) haveGuest() bool  {
	if l.UserInfo.Role >= dbmanager.RoleGuest && l.UserInfo.Role <= dbmanager.RoleAdmin {
		return true
	}
	return false
}

func (l *LoginCtr) haveManager() bool {
	if l.UserInfo.Role >= dbmanager.RoleManager && l.UserInfo.Role <= dbmanager.RoleAdmin {
		return true
	}
	return false
}

// LoginCtr.Admin 表示admin权限可以操作
func (l *LoginCtr) Admin() bool {
	logs.Debug(l.Ctx.Request.URL)
	l.checkReferer()
	l.checkLogin()

	logs.Debug("Role: %d", l.UserInfo.Role)
	if l.isAdmin() == false {
		l.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeAuthErr, "this action must be admin", nil)
		l.ServeJSON()
		l.StopRun()
		return false
	}

	return true
}

// LoginCtr.Manager 表示Manager权限可以操作
func (l *LoginCtr) Manager() bool {
	logs.Debug(l.Ctx.Request.URL)
	l.checkReferer()
	l.checkLogin()

	logs.Debug("Role: %d", l.UserInfo.Role)
	if l.haveManager() == false {
		l.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeAuthErr, "this action must have manager", nil)
		l.ServeJSON()
		l.StopRun()
		return false
	}

	return true
}

// LoginCtr.Guest 表示Guest权限可以操作
func (l *LoginCtr) Guest() bool {
	logs.Debug(l.Ctx.Request.URL)
	l.checkReferer()
	l.checkLogin()

	logs.Debug("Role: %d", l.UserInfo.Role)
	if l.haveGuest() == false {
		l.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeAuthErr, "this action must be guest over", nil)
		l.ServeJSON()
		l.StopRun()
		return false
	}

	return true
}

func (l *LoginCtr) DealPage() (offset int, limit int) {

	page, err := l.GetInt("page", upage.PageNoDefault)
	if err != nil {
		logs.Error(fmt.Sprintf("get 'page' param error: %s", err.Error()))
	}
	perPage, err := l.GetInt("page_count", upage.PageSizeDefault)
	if err != nil {
		logs.Error(fmt.Sprintf("get 'page_count' param error: %s", err.Error()))
	}
	offset, limit = upage.GetOffsetLimit(page, perPage)

	return
}

func (l *LoginCtr) Unmarshal(v interface{}) error {

	body, err := ioutil.ReadAll(l.Ctx.Request.Body)
	if err != nil {
		return err
	}
	if err := json.Unmarshal(body, v); err != nil {
		return err
	}
	return nil
}